package com.example.demovote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demovote.entity.Items;
import com.example.demovote.entity.Record;
import com.example.demovote.entity.Vote;
import com.example.demovote.mapper.ItemsMapper;
import com.example.demovote.mapper.RecordMapper;
import com.example.demovote.mapper.VoteMapper;
import com.example.demovote.service.IVoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demovote.vo.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 投票系统-题目表-2 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements IVoteService {

    @Resource
    ItemsMapper itemsMapper;
    @Resource
    VoteMapper voteMapper;

    @Override
    @Transactional // 事务控制注解
    public Result create(String vname, String vtype, String[] iname) {
        if(vname==null || vname.trim().isEmpty()){
            return new Result(0,"请输入标题！",null);
        }
        if(iname==null || iname.length < 2){
            return new Result(-1,"选项至少是个！",null);
        }
        // 其他验证请自行扩展
        Vote vote = new Vote();
        vote.setVname(vname);
        vote.setVtype(vtype);
        voteMapper.insert(vote);

        Items items = new Items();
        items.setVid(vote.getId());
        for (String i : iname) {
            if(i==null || i.trim().isEmpty()){
                return new Result(-2,"不能有空选项！",null);
            }
            items.setId(null);
            items.setIname(i);
            itemsMapper.insert(items);
        }
        return new Result(1,"投票添加成功！",vote);
    }

    @Resource
    RecordMapper recordMapper;

    @Override
    @Transactional // 事务控制注解
    public Result commit(int vid, int uid, int[] iid) {
        LambdaQueryWrapper<Record> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Record::getVid, vid);
        lqw.eq(Record::getUsid, uid);
        if (recordMapper.selectCount(lqw)>0) {
            return new Result(-1,"您已经投过票了！",null);
        }

        if(iid==null ||iid.length==0){
            return new Result(0,"请选择选项",null);
        }

        Record record = new Record();
        record.setVid(vid);
        record.setUsid(uid);
        for (int i : iid) {
            record.setId(null);
            record.setIid(i);
            recordMapper.insert(record);
        }
        return new Result(1,"投票成功！",null);
    }
}
